# 启动界面主程序
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QTimer
from ui_control2 import Ui_MainWindow
from soft_keyboard import SoftKeyboard
from soft_num_keyboard import SoftNumKeyboard
import utils
import signal

FOCUSIN  = 10
FOCUSOUT = 11
class ControlWindow(QMainWindow):
	def __init__(self):
		super().__init__()
		signal.signal(signal.SIGINT, self.handle_sigint)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.hc = utils.HardwareController
		utils.load_config()
		# 启动时检查串口连接情况
		serial_status = utils.check_serial_port()
		self.ui.label_5.setText(serial_status)
		self.timer = QTimer(self)
		self.timer.timeout.connect(self.query_temperatures)

		self.num_key_obj_lst = [
			self.ui.lineEdit_3,
			self.ui.lineEdit_2,
			self.ui.lineEdit_4,
			self.ui.lineEdit_5,
			self.ui.lineEdit_6,
			self.ui.lineEdit_7,
			self.ui.lineEdit_13,
			self.ui.lineEdit_8,
			self.ui.lineEdit_14,
			self.ui.lineEdit_9,
			self.ui.lineEdit_10,
			self.ui.lineEdit_11,
			self.ui.lineEdit_12,
			 ]
		self.key_obj_lst = [
			self.ui.plainTextEdit,
			self.ui.lineEdit,
			self.ui.textBrowser,
			self.ui.textBrowser_2,
			 ]
		for obj in self.num_key_obj_lst:
			obj.installEventFilter(self)
		for obj in self.key_obj_lst:
			obj.installEventFilter(self)
		self.soft_keyboard = SoftKeyboard()
		self.soft_num_keyboard = SoftNumKeyboard()

		# 控制台发送命令
		self.ui.pushButton.clicked.connect(self.send_console_command)

	def send_console_command(self):
		text = self.ui.plainTextEdit.toPlainText().strip()
		if not text:
			return
		import subprocess
		try:
			result = subprocess.run(text, shell=True, capture_output=True, text=True)
			output = result.stdout + result.stderr
		except Exception as e:
			output = str(e)
		self.ui.textBrowser.append(f"$ {text}\n{output}")
		self.ui.plainTextEdit.clear()
	def eventFilter(self, obj, event):
		if obj in self.num_key_obj_lst:
			if event.type() == FOCUSIN:
				self.soft_num_keyboard.set_target(obj)
				self.soft_num_keyboard.show_keyboard()
		elif obj in self.key_obj_lst:
			if event.type() == FOCUSIN:
				self.soft_keyboard.set_target(obj)
				self.soft_keyboard.show_keyboard()
		return super().eventFilter(obj, event)
	def query_temperatures(self):
		print("Hi there")
	def handle_sigint(self, signum, frame):
		print("SIGINT received, stopping timer...")
		QApplication.quit()

if __name__ == "__main__":
	app = QApplication(sys.argv)
	window = ControlWindow()
	window.show()
	sys.exit(app.exec())
